var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken')
const moment = require('moment')
const accountModel = require('../../models/accountModel')
const checktokenMiddleware = async (req, res, next) => {
    let token = req.get('token')
    if (!token) {
        return res.json({
            code: '2003',
            msg: 'token获取失败',
            data: null
        })
    } else {
        const p = await jwt.verify(token, 'yuhongyu')
        if (!p) {
            return res.json({
                code: '2004',
                msg: 'token校验失败',
                data: null
            })
        }
        next()
    }
}
router.get('/account', checktokenMiddleware, async function (req, res, next) {

    try {
        const p = await accountModel.find().sort({time: -1})
        res.json({
            "code": "0000",
            "msg": "读取成功",
            "data": p
        })
    } catch (error) {
        res.json({
            code: '1001',
            msg: '读取失败',
            data: null
        })

    }

});
router.delete('/account/:id', checktokenMiddleware, async function (req, res, next) {
    let id = req.params.id
    try {
        const p = await accountModel.deleteOne({_id: id})
        res.json({
            code: '0000',
            msg: '删除成功',
            data: null
        })
    } catch (error) {
        res.json({
            code: '1003',
            msg: '删除失败',
            data: null
        })
    }

});
router.post('/account', checktokenMiddleware, async function (req, res, next) {
    try {
        const p = await accountModel.create({
            ...req.body,
            time: moment(`${req.body.time}`).toDate()
        })
        console.log(req.body)
        res.json({
            code: '0000',
            msg: '创建成功',
            data: p
        })
    } catch (error) {
        res.json({
            code: '1002',
            msg: '创建失败',
            data: null
        })
    }

});
router.get('/account/:id', checktokenMiddleware, async function (req, res, next) {
    let id = req.params.id
    try {
        const p = await accountModel.findById(id)
        res.json({
            code: '0000',
            msg: '查询成功',
            data: p
        })
    } catch (error) {
        res.json({
            code: '1004',
            msg: '查询失败',
            data: null
        })
    }

});
router.patch('/account/:id', checktokenMiddleware, async function (req, res, next) {
    let id = req.params.id
    try {
        const p = await accountModel.updateOne({_id: id}, req.body)
        const data = await accountModel.findById(id)
        res.json({
            code: '0000',
            msg: '更新成功',
            data: data
        })
    } catch (error) {
        res.json({
            code: '1005',
            msg: '查询失败',
            data: null
        })
    }

});

module.exports = router;
